package dt.inlee.diancan.action;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import dt.inlee.common.util.BaseUtil;
import dt.inlee.diancan.service.DiancanService;
import dt.inlee.diancan.vo.OrderStatistics;
import dt.inlee.diancan.vo.ResponseAdminBean;
import dt.inlee.domain.DcBout;
import dt.inlee.domain.DcBusiness;
import dt.inlee.domain.DcFood;
import dt.inlee.domain.DcOrder;
import dt.inlee.domain.DcUser;

@Results({@Result(name = "success", location = "/page/diancan/index.jsp")})
@Namespace("/diancan")
@Controller("diancanAction")
public class DiancanAction extends ActionSupport {

    /**
     * @Fields serialVersionUID : TODO()
     */
    private static final long serialVersionUID = -4881251815467599929L;

    @Autowired
    private DiancanService diancanService;

    private DcBout bout;

    private DcBusiness business;

    private DcUser user;

    private DcOrder myOrder;// 本轮次我的订单

    private String error;

    private String errorUrl;// 出错跳转页面

    private ResponseAdminBean admin;

    public DcBout getBout() {
        return bout;
    }

    public void setBout(DcBout bout) {
        this.bout = bout;
    }

    public DcBusiness getBusiness() {
        return business;
    }

    public void setBusiness(DcBusiness business) {
        this.business = business;
    }

    public DcUser getUser() {
        return user;
    }

    public void setUser(DcUser user) {
        this.user = user;
    }

    public DcOrder getMyOrder() {
        return this.myOrder;
    }

    public String getError() {
        if (this.error == null) {
            return null;
        }
        try {
            return URLDecoder.decode(this.error, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            // e.printStackTrace();
            return null;
        }
    }

    public void setError(String error) {
        this.error = error;
    }

    public ResponseAdminBean getAdmin() {
        return admin;
    }

    public void setAdmin(ResponseAdminBean admin) {
        this.admin = admin;
    }

    public DiancanAction() {
        HttpServletRequest request = ServletActionContext.getRequest();
        user = (DcUser) ActionContext.getContext().getSession().get("diancanren");
        if (!request.getServletPath().equals("/diancan/index")) {// 没有输入用户名不能进入首页以外页面
            if (user == null) {
                this.error = "请输入姓名";
                this.errorUrl = "index";
            }
            bout = (DcBout) ActionContext.getContext().getSession().get("diancanbout");
            if (!request.getServletPath().equals("/diancan/main")) {// 下订单必须有轮次
                if (bout == null) {
                    this.error = "今天点餐尚未开始或已结束";
                    this.errorUrl = "index";
                }
            }
        }
    }

    /**
     * 
     * @方法名: index
     * @功能说明: TODO(首页)
     * @作者: 研发部-鄢松涛
     * @时间: 2014年9月23日下午3:50:44
     * @return
     */
    @Action(value = "index", results = {@Result(name = "success", location = "/page/diancan/index.jsp"),
            @Result(name = "main", type = "redirect", location = "/diancan/main")})
    public String index() {
        if (error != null && error != "") {
            return SUCCESS;
        }
        if (this.user == null) {
            String username = ServletActionContext.getRequest().getParameter("username");
            if (!BaseUtil.isEmpty(username)) {
                DcUser _user = diancanService.findUserByName(username);
                if (_user == null) {
                    this.error = "用户不存在，请确认姓名，以公司通讯录为准";
                    return SUCCESS;
                    /*
                     * _user = new DcUser(); _user.setName(username); diancanService.saveOrUpdateByUser(_user); _user = diancanService.findUserByName(username);
                     * ActionContext.getContext().getSession().put("diancanren", _user); return "main";
                     */
                } else {
                    this.error = null;
                    ActionContext.getContext().getSession().put("diancanren", _user);
                    return "main";
                }
            }
        } else {
            return "main";
        }
        return SUCCESS;
    }

    /**
     * 
     * @方法名: main
     * @功能说明: TODO(主页面)
     * @作者: 研发部-鄢松涛
     * @时间: 2014年9月23日下午3:50:36
     * @return
     */
    @Action(value = "main", results = {@Result(name = "success", location = "/page/diancan/main.jsp"),
            @Result(name = "index", location = "/page/diancan/index.jsp")})
    public String main() {
        if (this.errorUrl != null && this.errorUrl != "") {
            return this.errorUrl;
        }
        this.bout = diancanService.getBout();
        if (this.bout == null) {
            this.error = "今天点餐尚未开始或已结束";
            return "index";
        }
        ActionContext.getContext().getSession().put("diancanbout", bout);
        this.business = this.bout.getBusiness();
        diancanService.foodSort(this.business);// 给菜单排序
        this.myOrder = diancanService.findOrderByUser(user.getId(), bout.getId());
        long countdown = (bout.getEndTime().getTime() - System.currentTimeMillis()) / 1000;
        ServletActionContext.getRequest().setAttribute("countdown", countdown);// 剩余时间

        // 订单统计
        Map<String, OrderStatistics> orderStatistics = new HashMap<String, OrderStatistics>();
        int allNum = 0;
        double allPrice = 0;
        for (DcOrder order : bout.getOrders()) {
            OrderStatistics os = orderStatistics.get(order.getFood().getName());
            if (os != null) {
                os.setNum(os.getNum() + 1);
                os.setPrice(os.getPrice() + os.getFood().getPrice());
            } else {
                os = new OrderStatistics();
                os.setNum(1);
                os.setPrice(order.getFood().getPrice());
                os.setFood(order.getFood());
                orderStatistics.put(order.getFood().getName(), os);
            }
            allNum++;
            allPrice += order.getFood().getPrice();
        }
        ServletActionContext.getRequest().setAttribute("orderStatistics", orderStatistics);// 统计订单
        ServletActionContext.getRequest().setAttribute("allNum", allNum);// 统计订单
        ServletActionContext.getRequest().setAttribute("allPrice", allPrice);// 统计订单
        return SUCCESS;
    }


    /**
     * 
     * @方法名: order
     * @功能说明: TODO(处理订单)
     * @作者: 研发部-鄢松涛
     * @时间: 2014年9月23日下午3:50:24
     * @return
     */
    @Action(value = "order", results = {
            @Result(name = "success", type = "redirect", location = "/diancan/main", params = {"error", "${error}",
                    "encode", "true"}),
            @Result(name = "index", location = "/page/diancan/index.jsp", params = {"error", "${error}", "encode",
                    "true"})})
    public String order() {
        if (this.errorUrl != null && this.errorUrl != "") {
            return this.errorUrl;
        }
        long countdown = (bout.getEndTime().getTime() - System.currentTimeMillis()) / 1000;
        if (countdown < 0) {
            this.error = "本次点餐已结束";
            return SUCCESS;
        }
        String foodId_ = ServletActionContext.getRequest().getParameter("foodId");
        if (foodId_ != null && foodId_ != "") {
            int foodId = Integer.parseInt(foodId_);
            DcOrder order = diancanService.findOrderByUser(user.getId(), bout.getId());
            if (order == null) {
                order = new DcOrder();
                order.setUser(user);
                order.setBout(bout);
            }
            DcFood food = diancanService.findFoodById(foodId, bout.getBusiness().getId());
            if (food != null) {
                order.setFood(food);
                order.setCreateTime(new Date());
                diancanService.saveOrUpdateByOrder(order);
                return SUCCESS;
            } else {
                this.error = "你选的食物不存在";
                return SUCCESS;
            }
        }
        this.error = "参数错误";
        return SUCCESS;
    }

    /**
     * 
     * @方法名: giveUpOrder
     * @功能说明: TODO(放弃点餐)
     * @作者: 研发部-鄢松涛
     * @时间: 2014年9月27日下午12:18:27
     * @return
     */
    @Action(value = "giveUpOrder", results = {@Result(name = "success", type = "redirect", location = "/diancan/main")})
    public String giveUpOrder() {
        if (this.errorUrl != null && this.errorUrl != "") {
            return this.errorUrl;
        }
        DcOrder order = diancanService.findOrderByUser(user.getId(), bout.getId());
        if (order != null) {
            diancanService.deleteOrder(order);
        }
        return SUCCESS;
    }

    /**
     * 
     * @方法名: loginOut
     * @功能说明: TODO(退出)
     * @作者: 研发部-鄢松涛
     * @时间: 2014年9月27日下午2:26:38
     * @return
     */
    @Action(value = "loginOut", results = {@Result(name = "success", type = "redirect", location = "/diancan/index")})
    public String loginOut() {
        ActionContext.getContext().getSession().put("diancanren", null);
        return SUCCESS;
    }

    /**
     * 
     * @方法名: manage
     * @功能说明: TODO(管理)
     * @作者: 研发部-鄢松涛
     * @时间: 2014年10月9日上午9:17:49
     * @return
     */
    @Action(value = "admin", results = {
            @Result(name = "success", location = "/page/diancan/admin.jsp"),
            @Result(name = "index", type = "redirect", location = "/diancan/index", params = {"error", "${error}",
                    "encode", "true"})})
    public String admin() {
        if (this.errorUrl != null && this.errorUrl != "") {
            return this.errorUrl;
        }
        if (!this.user.getName().equals("鄢松涛")) {
            return "index";
        }
        this.bout = diancanService.getBout();
        admin = new ResponseAdminBean();
        admin.setBusiness(diancanService.gerAllBusiness());
        admin.setStartTime(new Date());
        Calendar c = Calendar.getInstance();
        c.set(Calendar.HOUR_OF_DAY, 11);
        c.set(Calendar.MINUTE, 25);
        admin.setEndTime(c.getTime());
        return SUCCESS;
    }

    /**
     * 
     * @方法名: newBout
     * @功能说明: TODO(新建或修改一个轮次)
     * @作者: 研发部-鄢松涛
     * @时间: 2014年10月14日上午11:03:32
     * @return
     */
    @Action(value = "newBout", results = {
            @Result(name = "success", type = "redirect", location = "/diancan/main"),
            @Result(name = "error", type = "redirect", location = "/diancan/admin", params = {"error", "${error}",
                    "encode", "true"})})
    public String newBout() {
        if (BaseUtil.isEmpty(admin.getNewBout().getEndTime())) {
            this.error = "参数错误";
            return "error";
        }
        if (BaseUtil.isEmpty(admin.getNewBout().getId())) {
            if (BaseUtil.isEmpty(admin.getNewBout().getBusiness())
                    || BaseUtil.isEmpty(admin.getNewBout().getStartTime())) {
                this.error = "参数错误";
                return "error";
            }
            admin.getNewBout().setStatus(1);
            diancanService.addBout(admin.getNewBout());
        } else {
            bout.setEndTime(admin.getNewBout().getEndTime());
            diancanService.updateBout(bout);
        }
        return SUCCESS;
    }

}
